package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.basic.util.TyplmLoggerUtil;
import com.hustcad.plm.caddoc.mapper.TyplmCADBuildHistoryMapper;
import com.hustcad.plm.caddoc.mapper.TyplmCADBuildRuleMapper;
import com.hustcad.plm.caddocapi.service.TyplmCADBuildHistoryService;
import com.hustcad.plm.pdm.basedrule.service.TyplmBasedRuleService;
import com.hustcad.plm.pdm.basedrule.vo.TyplmBasedLifeStageVO;
import com.hustcad.plm.pdm.caddoc.model.dto.CadBuildHistoryDTO;
import com.hustcad.plm.pdm.common.model.dto.BasicObjectDTO;
import com.hustcad.plm.pdm.common.model.vo.BusinessObjectVO;
import com.hustcad.plm.pdm.common.model.vo.iteration.CommonIteratorVO;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocDetails;
import com.hustcad.plm.pdm.ec.mapper.TyplmChgActRelDataLinkMapper;
import com.hustcad.plm.pdm.ec.mapper.TyplmChgActivityMapper;
import com.hustcad.plm.pdm.ec.mapper.TyplmChgNoticeActivityLinkMapper;
import com.hustcad.plm.pdm.ec.module.constant.TyChangeMngConstant;
import com.hustcad.plm.pdm.ec.module.dto.CreateECADTO;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.ec.module.vo.ChgActivityVO;
import com.hustcad.plm.pdm.ec.module.vo.ChgFormVO;
import com.hustcad.plm.pdm.ec.module.vo.ChgNoticeVO;
import com.hustcad.plm.pdm.ec.module.vo.ECObjDataVO;
import com.hustcad.plm.pdm.ec.service.*;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeService;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.intelplmapp.service.TyplmAppDocService;
import com.hustcad.plm.pdm.iteration.service.TyplmCommonIterateService;
import com.hustcad.plm.pdm.iteration.service.TyplmIterationService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.mpmlink.service.TyplmMpmWorkFlowAdaptationService;
import com.hustcad.plm.pdm.partbom.dto.CalculatePartRootDTO;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomFlowObjectService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartRelObjectService;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.hustcad.plm.pdm.workflow.model.constant.WorkFlowContainerStatusEnum;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainer;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmFlowContainerObjectService;
import com.hustcad.plm.pdm.workflow.service.TyplmFlowObjectTaskLinkService;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.common.ITyChangeable;
import com.ty.basic.common.ITyIterated;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.cad.CADBuildHistoryDO;
import com.ty.basic.entity.cad.CADBuildRuleDO;
import com.ty.basic.entity.change.*;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.type.TypeDO;
import com.ty.basic.handler.exceptionhandler.exception.ResponseCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.TyException;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.util.EntityBaseUtil;
import com.ty.basic.util.TyEntityMapperUtil;
import com.ty.basic.utils.BatchQueryHelper;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.entity.*;
import cqrtplm.mapper.*;
import cqrtplm.service.RTReviseObjectByEcnService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RTReviseObjectByEcnServiceImpl implements RTReviseObjectByEcnService {
    private static final int MAX_RETRY = 150; //设置最大重试次数防止死循环
    @Resource
    private TyplmChangeObjectLinkService typlmChangeObjectLinkService;
    @Resource
    private TyplmChgNoticeQueryService typlmChgNoticeQueryService;
    @Resource
    private TyplmChgActRelDataLinkMapper typlmChgActRelDataLinkMapper;
    @Resource
    private TyplmChangeLinkService typlmChangeLinkService;
    @Resource
    private TyplmIterationService typlmIterationService;
    @Resource
    private TyplmCommonIterateService typlmCommonIterateService;
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private TyplmChgActRecordLinkService typlmChgActRecordLinkService;
    @Resource
    private TyplmChgNoticeActivityLinkMapper typlmChgNoticeActivityLinkMapper;
    @Resource
    private TyplmChgActivityMapper typlmChgActivityMapper;
    @Resource
    private TyplmEngineeringChangeService typlmEngineeringChangeService;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private TyplmChgActivityService typlmChgActivityService;
    @Resource
    private TyplmChgNoticeActivityLinkService typlmChgNoticeActivityLinkService;
    @Resource
    private TyplmFlowContainerObjectService typlmFlowContainerObjectService;
    @Resource
    private TyplmPartBomFlowObjectService typlmPartBomFlowObjectService;
    @Resource
    private TyplmMpmWorkFlowAdaptationService typlmMpmWorkFlowAdaptationService;
    @Resource
    private TyChangeExtService tyChangeExtService;
    @Resource
    private TyplmFlowObjectTaskLinkService typlmFlowObjectTaskLinkService;
    @Resource
    private TyplmBasedRuleService typlmBasedRuleService;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private TyplmChgActivityQueryService typlmChgActivityQueryService;
    @Resource
    private TyplmUserService typlmUserService;
    @Resource
    private RTChangeMapper rtChangeMapper;
    @Resource
    private TyplmChgActRelDataLinkService typlmChgActRelDataLinkService;
    @Resource
    private TyplmPdmPartService typlmPdmPartService;
    @Resource
    private TyplmAttributeService typlmAttributeService;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmPartRelObjectService typlmPartRelObjectService;
    @Resource
    private TyplmCADBuildHistoryMapper typlmCADBuildHistoryMapper;
    @Resource
    private TyplmCADBuildRuleMapper typlmCADBuildRuleMapper;
    @Resource
    private TyplmCADBuildHistoryService typlmCADBuildHistoryService;
    @Resource
    private RtChangeaffectEbomMapper rtChangeaffectEbomMapper;
    @Resource
    private RtChangeaffectFinishedbomMapper rtChangeaffectFinishedbomMapper;
    @Resource
    private RtChangeaffectDrawingdocumentMapper rtChangeaffectDrawingdocumentMapper;
    @Resource
    private RtChangeaffectAssociatedbomMapper rtChangeaffectAssociatedbomMapper;
    @Resource
    private RtChangeaffectChangeobjectMapper rtChangeaffectChangeobjectMapper;
    @Resource
    private TyplmDocumentService typlmDocumentService;
    /**
     * @param workflowContainerOid
     */
    @Transactional
    @Override
    public void reviseEcaObjectByEcn(BigInteger workflowContainerOid) {
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(workflowContainerOid);
        if (!(workFlowContainerView instanceof FlowChgFormView)) {
            return;
        }
        FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
        ChgFormVO chgFormVO = flowChgFormView.getChgFormVO();
        String changeNo = chgFormVO.getObjectNumber();
        List<ECObjData> ecAffectVOS = chgFormVO.getEcAffectVOS();
//        List<ECObjData> ebomDataVOS = ecAffectVOS.stream().filter(ecObjData -> "EBOM号".contains(ecObjData.getTypeDefName())).collect(Collectors.toList());
//        List<ECObjData> cadDataVOS = ecAffectVOS.stream().filter(ecObjData -> TableTypeConstrant.TY_CADDOC_OTYPE.contains(ecObjData.getOtype())).collect(Collectors.toList());

        List<ChgActivityDO> chgActivityDOList = this.typlmChgNoticeActivityLinkService.queryECAByECNId(chgFormVO.getOid());
        ChgActivityDO chgActivityDO = null;
        if (chgActivityDOList != null && !chgActivityDOList.isEmpty()) {
            chgActivityDO = chgActivityDOList.get(0);
        }
        //获取ECN初始ECA的变更前对象
        List<ChgActRelDataLinkDO> actRelDataLinkDOList = this.typlmChgActRelDataLinkService.queryChgActRelDataLinkDO(chgFormVO.getOid(), (List) null);
        //获取ECN初始ECA的变更后对象
        List<ChgActRecordLinkDO> recordLinkDOS = this.typlmChgActRecordLinkService.queryObjOidAndOtypeByECAId(chgActivityDO.getOid());
        List<RtChangeaffectChangeobjectDO> affectList = rtChangeaffectChangeobjectMapper.queryByChangeNoAndPartNo(changeNo, "");
//        //受影响的EBOM
//        List<RtChangeaffectEbomDO> rtChangeaffectEbomDOS = this.rtChangeaffectEbomMapper.queryByChangeNoAndPartNo(changeNo, "");
//        //受影响的成品BOM
//        List<RtChangeaffectFinishedbomDO> rtChangeaffectFinishedbomDOS = this.rtChangeaffectFinishedbomMapper.queryByChangeNoAndPartNo(changeNo, "");
//        //关联受影响的BOM
//        List<RtChangeaffectAssociatedbomDO> rtChangeaffectAssociatedbomDOS = this.rtChangeaffectAssociatedbomMapper.queryByChangeNoAndPartNo(changeNo, "");
//        //受影响的图纸
//        List<RtChangeaffectDrawingdocumentDO> rtChangeaffectDrawingdocumentDOS = this.rtChangeaffectDrawingdocumentMapper.queryByChangeNoAndPartNo(changeNo, "");
        if (CollUtil.isNotEmpty(actRelDataLinkDOList)) {
            List<ChgActRelDataLinkDO> cadDocAndDocLinkDOS = new ArrayList<>();
            List<ChgActRelDataLinkDO> partLinkDOS = new ArrayList<>();
            List<ChgActRelDataLinkDO> oldLinkDOS = new ArrayList<>();
            //获取需要删除的，无需升版的对象
            Map map = removeObjectMap(chgFormVO);
            List<ChgActRelDataLinkDO> partDataLinkDOS = actRelDataLinkDOList.stream().filter(item -> TableTypeConstrant.TY_PART_OTYPE.contains(item.getBotype())).collect(Collectors.toList());
            List<ChgActRelDataLinkDO> cadDataLinkDOS = actRelDataLinkDOList.stream().filter(item -> TableTypeConstrant.TY_CADDOC_OTYPE.contains(item.getBotype())).collect(Collectors.toList());
            List<ChgActRelDataLinkDO> docDataLinkDOS = actRelDataLinkDOList.stream().filter(item -> TableTypeConstrant.TY_DOC_OTYPE.contains(item.getBotype())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(partDataLinkDOS)){
                for (ChgActRelDataLinkDO ecObjData : partDataLinkDOS) {
                    PartDetailsVO partDetailsVO = typlmPdmPartService.queryPartDetailsForCO(ecObjData.getBoid(), ecObjData.getBotype());
                    String number=partDetailsVO.getObjectNumber();
                    String typename=partDetailsVO.getTypeName();
                    if (typename.equals("EBOM号")||typename.equals("成品码")) {
                        partLinkDOS.add(ecObjData);
                    }else if (typename.equals("物料码")||typename.equals("图样代号")) {
                        if (affectList.stream().anyMatch(item -> item.getPartnumber().equals(number)&&item.getRelationship().contains("父物料"))){
                            partLinkDOS.add(ecObjData);
                        }
                    }
                }
            }
            if (CollUtil.isNotEmpty(cadDataLinkDOS)){
                for (ChgActRelDataLinkDO ecObjData : cadDataLinkDOS) {
                    DocDetails docDetail = this.typlmDocumentService.queryDocDetails(ecObjData.getBoid(), ecObjData.getBotype());
                    String cadNumber=docDetail.getObjectNumber();
                    for (ChgActRelDataLinkDO partDataLinkDO : partDataLinkDOS) {
                        PartDetailsVO partDetailsVO = typlmPdmPartService.queryPartDetailsForCO(partDataLinkDO.getBoid(), partDataLinkDO.getBotype());
                        List<DocDetails> docDetails = this.typlmPartRelObjectService.queryPartRelatedDocInfo(partDataLinkDO.getBoid());
                        String partNumber=partDetailsVO.getObjectNumber();
                        String typename=partDetailsVO.getTypeName();
                        if (typename.equals("EBOM号")) {
                            if (docDetails.stream().anyMatch(item -> item.getObjectNumber().equals(cadNumber))){
                                cadDocAndDocLinkDOS.add(ecObjData);
                                break;
                            }
                        } else if (typename.equals("图样代号")) {
                            if (affectList.stream().anyMatch(item -> item.getPartnumber().equals(partNumber)&&item.getRelationship().contains("父物料"))){
                                if (docDetails.stream().anyMatch(item -> item.getObjectNumber().equals(cadNumber))){
                                    cadDocAndDocLinkDOS.add(ecObjData);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (CollUtil.isNotEmpty(docDataLinkDOS)){
                for (ChgActRelDataLinkDO ecObjData : docDataLinkDOS) {
                    cadDocAndDocLinkDOS.add(ecObjData);
                }
            }
            for (ChgActRelDataLinkDO ecObjData : actRelDataLinkDOList) {
//                BigInteger boid = ecObjData.getBoid();
//                String btype = ecObjData.getBotype();
//                String tableName1 = "";
//                String tableName2 = "";
//                String objNumber = "";
//                if (RTPlmConstant.PART_TYPE.equals(btype)) {
//                    tableName1 = "ty_part";
//                    tableName2 = "ty_partmaster";
//                    objNumber = "PARTNUMBER";
//                } else if (RTPlmConstant.CADDOC_TYPE.equals(btype)) {
//                    tableName1 = "ty_caddoc";
//                    tableName2 = "ty_caddocmaster";
//                    objNumber = "DOCNUMBER";
//                } else if (RTPlmConstant.DOC_TYPE.equals(btype)) {
//                    tableName1 = "ty_doc";
//                    tableName2 = "ty_docmaster";
//                    objNumber = "DOCNUMBER";
//                }
//                JSONObject json = this.rtChangeMapper.getObjectJsonByOid(tableName1, tableName2, objNumber, boid.toString());
//                String number = json.getString("OBJNUMBER");
//                String typename = json.getString("TYPENAME");
//                String patterncode = "";
//                if (RTPlmConstant.PART_TYPE.equals(btype)) {
//                    if (typename.equals("EBOM_NUM")||typename.equals("ProductCode")) {
//                        partLinkDOS.add(ecObjData);
//                    }else if (typename.equals("MaterialCode")||typename.equals("Standard")) {
//                        affectList=affectList.stream().filter(changeobjectDO -> changeobjectDO.getPartnumber().equals(number)).collect(Collectors.toList());
//                        for (RtChangeaffectChangeobjectDO changeobjectDO : affectList){
//                            String relationship = changeobjectDO.getRelationship();
//                            if(relationship.contains("父物料")){
//                                partLinkDOS.add(ecObjData);
//                            }
//                        }
//                    }
//                } else if (RTPlmConstant.CADDOC_TYPE.equals(btype)) {
//                    cadDocAndDocLinkDOS.add(ecObjData);
//                }else if (RTPlmConstant.DOC_TYPE.equals(btype)){
//                    cadDocAndDocLinkDOS.add(ecObjData);
//                }
//                if (RTPlmConstant.PART_TYPE.equals(btype)) {
//                    if (typename.equals("MaterialCode")) {
//                        patterncode = number.substring(0, number.lastIndexOf("-"));
//                        if (!map.isEmpty()) {
//                            if (!map.containsKey(number)&&!map.containsKey(patterncode)) {
//                                if (RTPlmConstant.PART_TYPE.equals(btype)) {
//                                    partLinkDOS.add(ecObjData);
//                                } else {
//                                    cadDocAndDocLinkDOS.add(ecObjData);
//                                }
//                            } else {
//                                oldLinkDOS.add(ecObjData);
//                            }
//                        } else {
//                            if (RTPlmConstant.PART_TYPE.equals(btype)) {
//                                partLinkDOS.add(ecObjData);
//                            } else {
//                                cadDocAndDocLinkDOS.add(ecObjData);
//                            }
//                        }
//                    }else{
//                        if (!map.isEmpty()) {
//                            if (!map.containsKey(number)) {
//                                if (RTPlmConstant.PART_TYPE.equals(btype)) {
//                                    partLinkDOS.add(ecObjData);
//                                } else {
//                                    cadDocAndDocLinkDOS.add(ecObjData);
//                                }
//                            } else {
//                                oldLinkDOS.add(ecObjData);
//                            }
//                        } else {
//                            if (RTPlmConstant.PART_TYPE.equals(btype)) {
//                                partLinkDOS.add(ecObjData);
//                            } else {
//                                cadDocAndDocLinkDOS.add(ecObjData);
//                            }
//                        }
//                    }
//                }else{
//                    cadDocAndDocLinkDOS.add(ecObjData);
//                }
            }
//            if(CollUtil.isNotEmpty(ebomDataVOS)){
//                for (ECObjData ecObjData : ebomDataVOS) {
//                    BigInteger oid = ecObjData.getOid();
//                    List<DocDetails> docDetails = this.typlmPartRelObjectService.queryPartRelatedDocInfo(oid);
//                    if(CollUtil.isNotEmpty(docDetails)){
//                        for (DocDetails docDetail : docDetails) {
//                            String docNumber = docDetail.getObjectNumber();
//                            if(cadDataVOS.stream().anyMatch(cadData -> cadData.getObjectNumber().equals(docNumber))){
//                                cadDocAndDocLinkDOS.add(ecObjData);
//                                break;
//                            }
//                        }
//                    }
//                }
//            }
            TyAccountContext.setIgnoreAuth(true);
            if (cadDocAndDocLinkDOS.size() > 0) {
                //升版变更对象并创建ECA
                reviseObjectAndCreateECA(chgFormVO, cadDocAndDocLinkDOS, "图文档");
            }
            if (partLinkDOS.size() > 0) {
                //升版变更对象创建ECA给流程发起者
                reviseObject(chgFormVO, chgActivityDO,recordLinkDOS, partLinkDOS, cadDocAndDocLinkDOS, "零部件");
            }

            //删除系统默认创建的ECA及ECA关联的数据
//            if (!CollUtil.isEmpty(chgActivityDOList)) {
//                Map<String, ChgActivityDO> ecaOwnerMap = (Map) chgActivityDOList.stream().collect(Collectors.toMap((item) -> item.getOid() + "_" + item.getOwneroid(), Function.identity(), (a, b) -> a));
//                if (CollUtil.isNotEmpty(ecaOwnerMap)) {
//                    List<ChgActivityVO> deleteList = Convert.toList(ChgActivityVO.class, ecaOwnerMap.values());
//                    this.typlmChgActivityService.batchDeleteEca(deleteList);
//                }
//            }
            TyAccountContext.setIgnoreAuth(false);
        }
    }

    /**
     * @param workflowContainerOid
     */
    @Override
    public void reviseEcaMbomsByEcn(BigInteger workflowContainerOid) {
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(workflowContainerOid);
        if (!(workFlowContainerView instanceof FlowChgFormView)) {
            return;
        }
        FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
        ChgFormVO chgFormVO = flowChgFormView.getChgFormVO();
        List<ECObjData> ecObjDataVOS = chgFormVO.getEcObjDataVOS();
        List<ChgActivityDO> chgActivityDOList = this.typlmChgNoticeActivityLinkService.queryECAByECNId(chgFormVO.getOid());
        ChgActivityDO chgActivityDO = null;
        if (CollectionUtils.isNotEmpty(chgActivityDOList)) {
            for (ChgActivityDO chgActivityDO1 : chgActivityDOList) {
                String type = chgActivityDO1.getDescription();
                if ("零部件".equals(type)||StringUtils.isBlank(type)) {
                    chgActivityDO = chgActivityDO1;
                }
            }
        }
        //获取ECN初始ECA的变更前对象
        List<ChgActRelDataLinkDO> actRelDataLinkDOList = this.typlmChgActRelDataLinkService.queryChgActRelDataLinkDO(chgFormVO.getOid(), (List) null);
        Map<String, List<ChgActRelDataLinkDO>> linkEcaOwnerMap = (Map) actRelDataLinkDOList.stream().collect(Collectors.groupingBy((item) -> item.getAoid() + "_" + item.getOwneroid()));
        //获取ECN初始ECA的变更后对象
//        List<ChgActRecordLinkDO> recordLinkDOS = this.typlmChgActRecordLinkService.queryObjOidAndOtypeByECAId(
//                chgActivityDO.getOid());
        if (CollUtil.isNotEmpty(actRelDataLinkDOList)) {
            List<ChgActRelDataLinkDO> partLinkDOS = new ArrayList<>();
            for (ChgActRelDataLinkDO ecObjData : actRelDataLinkDOList) {
                BigInteger boid = ecObjData.getBoid();
                String btype = ecObjData.getBotype();
                if (RTPlmConstant.PART_TYPE.equals(btype)) {
                } else if (RTPlmConstant.CADDOC_TYPE.equals(btype)) {
                    continue;
                } else if (RTPlmConstant.DOC_TYPE.equals(btype)) {
                    continue;
                }
                PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(boid, btype);
                String typeName = detailsVO.getTypeName();
                String viewName = detailsVO.getView();
                if ("成品码".equals(typeName) && !"Design".equals(viewName)) {
                    partLinkDOS.add(ecObjData);
                }
            }
            TyAccountContext.setIgnoreAuth(true);
            if (partLinkDOS.size() > 0) {
                //升版变更对象并将升版后对象添加到变更后对象列表
                List<IdentifierEntity> identifierEntitieList = new ArrayList<>();
                if (CollUtil.isNotEmpty(partLinkDOS)) {
                    //将升版对象批量升版，并获取升版后对象
                    List<CommonIteratorVO> changeObjList = partLinkDOS.stream().map(item -> {
                        CommonIteratorVO commonIteratorVO = new CommonIteratorVO();
                        commonIteratorVO.setId(item.getBoid().toString());
                        commonIteratorVO.setTypeDefName(item.getBotype());
                        commonIteratorVO.setChangePolicy("Change");
                        return commonIteratorVO;
                    }).collect(Collectors.toList());
                    List<BusinessObjectVO> businessObjectVOList = typlmIterationService.batchNewVersionWithPolicy(changeObjList);
                    if (CollUtil.isNotEmpty(businessObjectVOList)) {
                        //更新IBA属性
                        updateBomlineAttrs(businessObjectVOList, chgFormVO.getObjectNumber());
                        List<IdentifierEntity> identifierEntities = businessObjectVOList.stream().map(item -> new IdentifierEntity(item.getId(), item.getOtype())).collect(Collectors.toList());
                        identifierEntitieList.addAll(identifierEntities);
                    }
                }
                if (CollUtil.isNotEmpty(identifierEntitieList)) {
                    List<ChgActRecordLinkDO> chgActRecordLinkDOList = new ArrayList<>();
                    //将变更后对象与ECA关联
                    List<BigInteger> ecaObjListOid = getEcaObjListOid(chgActivityDO);
                    for (IdentifierEntity identifierEntity : identifierEntitieList) {
                        BigInteger entityOid = identifierEntity.getOid();
                        if (ecaObjListOid.contains(entityOid)) {
                            continue;
                        }
                        buildEcAffectVOList(chgActivityDO, entityOid, identifierEntity.getOtype(), chgActRecordLinkDOList);
                    }
                    if (CollUtil.isNotEmpty(chgActRecordLinkDOList)) {
                        typlmChgActRecordLinkService.batchInsertSelective(chgActRecordLinkDOList);
                    }
                }
            }
            TyAccountContext.setIgnoreAuth(false);
        }
    }

    /**
     * 升版对象,将变更后对象添加到变更后对象列表中,创建ECA对象
     *
     * @param chgFormVO
     * @param actRelDataLinkDOList
     */
    public void reviseObjectAndCreateECA(ChgFormVO chgFormVO, List<ChgActRelDataLinkDO> actRelDataLinkDOList, String type) {
        TypeDO typeDO = this.typlmTypeService.getLastTypeByLogicalidentifier("ty.inteplm.change.CTyChangeActivity");
        TyplmBasedLifeStageVO firstStageByCondition = this.typlmBasedRuleService.getFirstStageByCondition(typeDO.getOid(), chgFormVO.getContainerOid(), chgFormVO.getContainerOtype());
        TyplmLoggerUtil.debug(log, () -> "根据类型的名称、容器的id和容器的类型获取初始化规则", () -> new Object[]{JSON.toJSONString(firstStageByCondition)});
        //        Map<String, List<ChgActRelDataLinkDO>> ownerMap = getOwnerMap(actRelDataLinkDOList);
        Map<String, List<ChgActRelDataLinkDO>> linkEcaOwnerMap = (Map) actRelDataLinkDOList.stream().collect(Collectors.groupingBy((item) -> item.getOwneroid().toString()));
        if (!linkEcaOwnerMap.isEmpty()) {
            for (String uid : linkEcaOwnerMap.keySet()) {
                UserDO userDO = this.typlmUserService.queryUserByKey(new BigInteger(uid));
                List<ChgActRelDataLinkDO> ecObjDataList = linkEcaOwnerMap.get(uid);
                List<IdentifierEntity> identifierEntitieList = new ArrayList<>();
                if (CollUtil.isNotEmpty(ecObjDataList)) {
                    List<CommonIteratorVO> changeObjList = ecObjDataList.stream().map(item -> {
                        CommonIteratorVO commonIteratorVO = new CommonIteratorVO();
                        commonIteratorVO.setId(item.getBoid().toString());
                        commonIteratorVO.setTypeDefName(item.getBotype());
                        commonIteratorVO.setChangePolicy("Change");
                        return commonIteratorVO;
                    }).collect(Collectors.toList());
                    List<BusinessObjectVO> businessObjectVOList = typlmIterationService.batchNewVersionWithPolicy(changeObjList);
                    if (CollUtil.isNotEmpty(businessObjectVOList)) {
                        //更新IBA属性
                        updateBomlineAttrs(businessObjectVOList, chgFormVO.getObjectNumber());
                        List<IdentifierEntity> identifierEntities = businessObjectVOList.stream().map(item -> new IdentifierEntity(item.getId(), item.getOtype())).collect(Collectors.toList());
                        identifierEntitieList.addAll(identifierEntities);
                    }
                }
                if (CollUtil.isNotEmpty(identifierEntitieList)) {
                    BigInteger oid = chgFormVO.getOid();
                    List<ChgActRecordLinkDO> chgActRecordLinkDOList = new ArrayList<>();
                    //                            ChgActivityDO chgActivityDO = getChgActivityDO(String.valueOf(oid));
                    CreateECADTO eca = this.buildEcaDTO(chgFormVO, userDO, firstStageByCondition.getTemplateEntity(), typeDO.getName(), type);
                    ChgActivityVO chgActivityVO = this.typlmChgActivityQueryService.queryECAByNumber(eca.getActivitynumber());
                    //将初始ECA的变更对象分发到新的ECA
                    for (ChgActRelDataLinkDO linkDO : ecObjDataList) {
                        linkDO.setAoid(chgActivityVO.getOid());
                        linkDO.setAotype(chgActivityVO.getOtype());
                        linkDO.setBranchid(chgActivityVO.getBranchid());
                        this.typlmChgActRelDataLinkService.updateChgActRelDataLinkDO(linkDO);
                    }
                    //将变更后对象与ECA关联
                    List<BigInteger> ecaObjListOid = getEcaObjListOid(chgActivityVO);
                    for (IdentifierEntity identifierEntity : identifierEntitieList) {
                        BigInteger entityOid = identifierEntity.getOid();
                        if (ecaObjListOid.contains(entityOid)) {
                            continue;
                        }
                        buildEcAffectVOList(chgActivityVO, entityOid, identifierEntity.getOtype(), chgActRecordLinkDOList);
                    }
                    if (CollUtil.isNotEmpty(chgActRecordLinkDOList)) {
                        typlmChgActRecordLinkService.batchInsertSelective(chgActRecordLinkDOList);
                    }
                }
            }
        }
    }

    private void updateBomlineAttrs(List<BusinessObjectVO> businessObjectVOList, String changeNo) {
        List<SaveObjIBADTO> objWithIbaList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(businessObjectVOList)) {
            for (BusinessObjectVO objectVO : businessObjectVOList) {
                String oid = objectVO.getId().toString();
                String otype = objectVO.getOtype();
                Map<String, List<String>> ibaAttributeMap = typlmAttributeService.getIbaAttributeMap(new BigInteger(oid), otype);
                if (MapUtils.isEmpty(ibaAttributeMap)) {
//                    continue;
                }
                if (ibaAttributeMap.containsKey("BusinessEdition")) {
                    List<String> strList = ibaAttributeMap.get("BusinessEdition");
                    ibaAttributeMap = new HashMap<>();
                    if (CollectionUtils.isNotEmpty(strList)) {
                        String businessEdition = strList.get(0);
                        if (StringUtils.isNotBlank(businessEdition) && businessEdition.contains("V")) {
                            String iterator = businessEdition.substring(1);
                            int iteratorNum = Integer.parseInt(iterator) + 1;
                            String newBusinessEdition = "V" + iteratorNum;
                            ibaAttributeMap.put("BusinessEdition", Arrays.asList(newBusinessEdition));
                        }
                    }
                }
                ibaAttributeMap.put("ChangeContent", Arrays.asList("变更单：" + changeNo));
                List<IbaDTO> objIbaList = buildSaveIbaDTO(ibaAttributeMap);
                CTyEntityBaseDO ctyEntityBaseDO = new CTyEntityBaseDO();
                ctyEntityBaseDO.setOid(oid);
                ctyEntityBaseDO.setOtype(otype);
                SaveObjIBADTO saveObjIBADTO = new SaveObjIBADTO();
                saveObjIBADTO.setCTyEntityBaseDO(ctyEntityBaseDO);
                saveObjIBADTO.setObjIbaList(objIbaList);
                objWithIbaList.add(saveObjIBADTO);
            }
        }
        if (CollectionUtils.isNotEmpty(objWithIbaList)) this.typlmAttributeValueService.batchSaveIBAByObjList(objWithIbaList, false);
    }

    /**
     * 升版对象并将变更后对象添加到变更后对象列表中
     *
     * @param chgFormVO
     * @param afterDataLinkDOS
     */
    public void reviseObject(ChgFormVO chgFormVO, ChgActivityDO chgActivityVO,List<ChgActRecordLinkDO> afterDataLinkDOS, List<ChgActRelDataLinkDO> actRelDataLinkDOList, List<ChgActRelDataLinkDO> oldLinkDOS, String type) {
        if (CollectionUtils.isNotEmpty(afterDataLinkDOS) || CollectionUtils.isNotEmpty(actRelDataLinkDOList) || CollectionUtils.isNotEmpty(oldLinkDOS)) {
            TypeDO typeDO = this.typlmTypeService.getLastTypeByLogicalidentifier("ty.inteplm.change.CTyChangeActivity");
            TyplmBasedLifeStageVO firstStageByCondition = this.typlmBasedRuleService.getFirstStageByCondition(typeDO.getOid(), chgFormVO.getContainerOid(), chgFormVO.getContainerOtype());
            TyplmLoggerUtil.debug(log, () -> "根据类型的名称、容器的id和容器的类型获取初始化规则", () -> new Object[]{JSON.toJSONString(firstStageByCondition)});
            List<IdentifierEntity> identifierEntitieList = new ArrayList<>();
            if (CollUtil.isNotEmpty(actRelDataLinkDOList)) {
                //将升版对象批量升版，并获取升版后对象
                List<CommonIteratorVO> changeObjList = actRelDataLinkDOList.stream().map(item -> {
                    CommonIteratorVO commonIteratorVO = new CommonIteratorVO();
                    commonIteratorVO.setId(item.getBoid().toString());
                    commonIteratorVO.setTypeDefName(item.getBotype());
                    commonIteratorVO.setChangePolicy("Change");
                    return commonIteratorVO;
                }).collect(Collectors.toList());
                List<BusinessObjectVO> businessObjectVOList = typlmIterationService.batchNewVersionWithPolicy(changeObjList);

                if (CollUtil.isNotEmpty(businessObjectVOList)) {
                    //更新IBA属性
                    updateBomlineAttrs(businessObjectVOList, chgFormVO.getObjectNumber());
                    List<IdentifierEntity> identifierEntities = businessObjectVOList.stream().map(item -> new IdentifierEntity(item.getId(), item.getOtype())).collect(Collectors.toList());
                    identifierEntitieList.addAll(identifierEntities);
                    //更新关联图纸
                    for (BusinessObjectVO objectVO : businessObjectVOList) {
                        BigInteger partId=objectVO.getId();
                        List<DocDetails> caddocList=this.typlmPartRelObjectService.queryPartRelatedDocInfo(partId);
                        if (CollUtil.isNotEmpty(caddocList)) {
                            for (DocDetails docDetails : caddocList) {
                              String buildRuleName=docDetails.getBuildRuleName();
                              boolean isBuildRule=docDetails.getIsBuildRule();
                              String number=docDetails.getNumber();
                              boolean isLatestVersion=docDetails.getIslatestVersion();
                              String isLastIterated=docDetails.getIslastiterated();
                              if (!isLatestVersion || !"Y".equals(isLastIterated)){
                                  if (isBuildRule){
                                      boolean isDeleted=deleteTheBuildRule(partId);
                                      if (isDeleted){
                                          JSONObject cadJSON=rtChangeMapper.queryLatestCADDocByCode(number);
                                          String cadId=cadJSON.getString("OID");
                                          CadBuildHistoryDTO cadBuildHistoryDTO=new CadBuildHistoryDTO();
                                          cadBuildHistoryDTO.setCadId(new BigInteger(cadId));
                                          cadBuildHistoryDTO.setPartId(partId);
                                          cadBuildHistoryDTO.setBuildtype(7l);
                                          cadBuildHistoryDTO.setBuildRuleId(randomCodeGenerator());
                                          typlmCADBuildHistoryService.batchInsert(Arrays.asList(cadBuildHistoryDTO));
                                       }
                                  }
                              }
                            }
                        }
                    }
                }
            }
//            if (CollUtil.isNotEmpty(actRelDataLinkDOList)) {
//                //将初始ECA已经升版的变更对象分发到新的ECA
//                for (ChgActRelDataLinkDO linkDO : actRelDataLinkDOList) {
//                    linkDO.setAoid(chgActivityVO.getOid());
//                    linkDO.setAotype(chgActivityVO.getOtype());
//                    linkDO.setBranchid(chgActivityVO.getBranchid());
//                    this.typlmChgActRelDataLinkService.updateChgActRelDataLinkDO(linkDO);
//                }
//            }
            if (CollUtil.isNotEmpty(oldLinkDOS)) {
                //将初始ECA的不需要升版的对象分发到ECA
                List<CTyEntityBaseDO> entityBaseDOList = new ArrayList<>();
                for (ChgActRelDataLinkDO linkDO : oldLinkDOS) {
                    CTyEntityBaseDO entityBaseDO=new CTyEntityBaseDO();
                    entityBaseDO.setOid(linkDO.getBoid());
                    entityBaseDO.setOtype(linkDO.getBotype());
                    entityBaseDOList.add(entityBaseDO);
                }
                if (CollUtil.isNotEmpty(entityBaseDOList))
                    this.typlmChgActRelDataLinkService.batchDeleteChgRelDataLink(chgActivityVO.getOid(), entityBaseDOList);
            }
            //将ECA的初始ECA变更后对象与新ECA关联
//            if (CollectionUtils.isNotEmpty(afterDataLinkDOS)) {
//                for (ChgActRecordLinkDO chgActRecordLinkDO : afterDataLinkDOS) {
//                    chgActRecordLinkDO.setAoid(chgActivityVO.getOid());
//                    chgActRecordLinkDO.setAotype(chgActivityVO.getOtype());
//                    chgActRecordLinkDO.setBranchid(chgActivityVO.getBranchid());
//                    this.typlmChgActRecordLinkService.updateByPrimaryKey(chgActRecordLinkDO);
////                    chgActRecordLinkDOList.add(chgActRecordLinkDO);
//                }
//            }
            //将变更后对象与ECA关联
            List<ChgActRecordLinkDO> chgActRecordLinkDOList = new ArrayList<>();
            for (IdentifierEntity identifierEntity : identifierEntitieList) {
                BigInteger entityOid = identifierEntity.getOid();
                String entityOtype = identifierEntity.getOtype();
                buildEcAffectVOList(chgActivityVO, entityOid, entityOtype, chgActRecordLinkDOList);
            }
            if (CollUtil.isNotEmpty(chgActRecordLinkDOList)) {
                this.typlmChgActRecordLinkService.batchInsertSelective(chgActRecordLinkDOList);
            }
        }

    }

    /**
     * 获取变更对象中图纸对象的创建者MAP
     *
     * @param actRelDataLinkDOList
     */
    public Map<String, List<ChgActRelDataLinkDO>> getOwnerMap(List<ChgActRelDataLinkDO> actRelDataLinkDOList) {
        Map<String, List<ChgActRelDataLinkDO>> ownerDrawingMap = new HashMap<>();
        for (ChgActRelDataLinkDO dataLinkDO : actRelDataLinkDOList) {
            BigInteger ownerOid = dataLinkDO.getOwneroid();
            String ownerotype = dataLinkDO.getOwnerotype();
            if (StringUtils.isNotEmpty(ownerotype) && ObjectUtil.isNotEmpty(ownerOid)) {
                List<ChgActRelDataLinkDO> list = null;
                if (ownerDrawingMap.containsKey(ownerotype + ":" + ownerOid)) {
                    list = ownerDrawingMap.get(ownerotype + ":" + ownerOid);
                } else {
                    list = new ArrayList<>();
                }
                list.add(dataLinkDO);
                ownerDrawingMap.put(ownerotype + ":" + ownerOid, list);
            }
        }
        return ownerDrawingMap;
    }

    @NotNull
    private CreateECADTO buildEcaDTO(ChgFormVO chgFormVO, UserDO user, IdentifierEntity templateEntity, String typeDefName, String type) {
        CreateECADTO eca = new CreateECADTO();
        TyAccountContext.setUser(user);
        eca.setUserDO(user);
        eca.setOtype("ty.inteplm.change.CTyChangeActivity");
        eca.setCreator(user.getName());
        eca.setOwner(user.getName());
        eca.setActivitynumber("eca" + System.currentTimeMillis());
        eca.setContaineroid(chgFormVO.getContainerOid());
        eca.setContainerotype(chgFormVO.getContainerOtype());
        eca.setEcoId(chgFormVO.getOid());
        eca.setLifecycletemplateoid(templateEntity.getOid());
        eca.setTypeDefName(typeDefName);
        eca.setDescription(type);
        TyplmLoggerUtil.debug(log, () -> "待创建的eca对象为==>【{}】", () -> new Object[]{JSON.toJSONString(eca)});
        this.typlmChgActivityService.batchCreateECA(Collections.singletonList(eca));
        return eca;
    }

    @Override
    public void reviseChgBeforeObjectByEca(BigInteger ecaId, List<ECObjDataVO> ecaBeforeObjectList) {
        IdentifierEntity identifierEntity = new IdentifierEntity();
        identifierEntity.setOid(ecaId);
        identifierEntity.setOtype("ty.inteplm.change.CTyChangeActivity");
        TyplmLoggerUtil.debug(log, () -> "eca标识为==>【{}】", () -> new Object[]{JSON.toJSONString(identifierEntity)});
        if (ObjectUtils.isEmpty(ecaBeforeObjectList)) {
            List<ECObjDataVO> drawingList = new ArrayList<>();
            ecaBeforeObjectList = this.typlmChangeObjectLinkService.queryECObjList(identifierEntity, true);
            for (ECObjDataVO dataVO : ecaBeforeObjectList) {
                String type = dataVO.getOtype();
                if (RTPlmConstant.CADDOC_TYPE.equals(type) || RTPlmConstant.DOC_TYPE.equals(type)) {
                    drawingList.add(dataVO);
                }
            }
            ecaBeforeObjectList = drawingList;
        }

        if (!CollUtil.isEmpty(ecaBeforeObjectList)) {
            List<ChgActRecordLinkDO> chgActRecordLinkDOList = this.typlmChgActRecordLinkService.queryObjOidAndOtypeByECAId(ecaId);
            Map<BigInteger, ChgActRecordLinkDO> recordLinkDOMap = (Map) chgActRecordLinkDOList.stream().collect(Collectors.toMap(ChgActRecordLinkDO::getBoid, (chgActRecordLinkDOx) -> chgActRecordLinkDOx, (k1, k2) -> k1));
            TyplmLoggerUtil.debug(log, () -> "根据eca获取的变更后关联对象为==>【{}】", () -> new Object[]{JSON.toJSONString(recordLinkDOMap)});
            List<IdentifierEntity> afterList = (List) chgActRecordLinkDOList.stream().map((item) -> new IdentifierEntity(item.getBoid(), item.getBotype())).collect(Collectors.toList());
            Map<IdentifierEntity, CTyEntityBaseDO> entityMap = CommonUtil.getEntityMap(afterList);

            for (ChgActRecordLinkDO chgActRecordLinkDO : chgActRecordLinkDOList) {
                IdentifierEntity identifierEntityRecord = new IdentifierEntity(chgActRecordLinkDO.getBoid(), chgActRecordLinkDO.getBotype());
                CTyEntityBaseDO cTyEntityBaseDO = (CTyEntityBaseDO) entityMap.get(identifierEntityRecord);
                if (cTyEntityBaseDO instanceof ITyChangeable && cTyEntityBaseDO instanceof ITyIterated) {
                    ITyIterated iTyIterated = (ITyIterated) cTyEntityBaseDO;
                    for (ECObjDataVO ecObjDataVO : ecaBeforeObjectList) {
                        if (ecObjDataVO.getMasteredoid().equals(iTyIterated.getMasteredoid()) && !ecObjDataVO.getBranchid().equals(iTyIterated.getBranchid())) {
                            return;
                        }
                    }
                }
            }

            TyAccountContext.setIgnoreAuth(true);
            ChgActivityDO chgActivityDO = this.typlmChgActivityService.selectByPrimaryKey(ecaId);
            List<IdentifierEntity> chgAfterObjectList = new ArrayList();
            Map<String, List<ECObjDataVO>> eCObjDataMap = (Map) ecaBeforeObjectList.stream().collect(Collectors.groupingBy(ECObjDataVO::getOtype));
            this.reviseMpmObject(eCObjDataMap, ecaBeforeObjectList, chgAfterObjectList);
            List<BasicObjectDTO> lastVersionObjMap = new ArrayList();

            for (Map.Entry<String, List<ECObjDataVO>> entry : eCObjDataMap.entrySet()) {
                List<ECObjDataVO> ecObjDataVOS = (List) entry.getValue();
                List<BigInteger> masteredIdList = (List) ecObjDataVOS.stream().map(ECObjDataVO::getMasteredoid).collect(Collectors.toList());
                if (!org.springframework.util.CollectionUtils.isEmpty(masteredIdList)) {
                    lastVersionObjMap.addAll(this.typlmCommonIterateService.batchQueryObjLastVersionByMasterId(masteredIdList, (String) entry.getKey()));
                }
            }

            TyplmLoggerUtil.debug(log, () -> "最新小版本对象为==>【{}】", () -> new Object[]{JSON.toJSONString(lastVersionObjMap)});
            this.batchInitChgAfterObjectList(ecaBeforeObjectList, chgActivityDO.getCreatoroid(), lastVersionObjMap, recordLinkDOMap, chgAfterObjectList);
            if (CollUtil.isNotEmpty(chgAfterObjectList)) {
                this.createEcaLinkChgAfterObject(ecaId, chgAfterObjectList);
            }

            TyAccountContext.setIgnoreAuth(false);
            this.buildAfterChangeObjDistribute(ecaId);
        }
    }


    public Map addAfterObjectMap(ChgFormVO chgFormVO) {
        Map map = new HashMap();
        //表单内容
        String formData = chgFormVO.getFormData();
        if (StringUtils.isNotBlank(formData)) {
            JSONObject formDataJson = JSONObject.parseObject(formData);
            JSONArray subform47946 = formDataJson.getJSONArray("subform47946");
            JSONArray subform57714 = formDataJson.getJSONArray("subform57714");
            if (CollectionUtils.isNotEmpty(subform47946)) {
                for (int i = 0; i < subform47946.size(); i++) {
                    String beforeChangeNo = subform47946.getJSONObject(i).getString("input67563");
                    String type = subform47946.getJSONObject(i).get("radio81926").toString();
                    String afterChangeNo = subform47946.getJSONObject(i).getString("radio73127");
                    if ("图号升级".equals(type)) {
                        JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(afterChangeNo, RTPlmConstant.VIEW_DESIGN);
                        if (afterChangeNoJson != null) {
                            String id = afterChangeNoJson.getString("OID");
                            String otype = afterChangeNoJson.getString("OTYPE");
                            map.put(beforeChangeNo, beforeChangeNo);
                        }
                    } else if ("图纸升版".equals(type)) {
                        JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(beforeChangeNo, RTPlmConstant.VIEW_DESIGN);
                        if (afterChangeNoJson != null) {
                            String id = afterChangeNoJson.getString("OID");
                            String otype = afterChangeNoJson.getString("OTYPE");
                            map.put(beforeChangeNo, beforeChangeNo);
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(subform57714)) {
                for (int i = 0; i < subform57714.size(); i++) {
                    String beforeChangeNo = subform57714.getJSONObject(i).getString("input36063");
                    String type = subform57714.getJSONObject(i).getString("input70284");
                    String afterChangeNo = subform57714.getJSONObject(i).getString("input37516");
                    if ("增加".equals(type)) {
                        JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(afterChangeNo, RTPlmConstant.VIEW_DESIGN);
                        if (afterChangeNoJson != null) {
                            String id = afterChangeNoJson.getString("OID");
                            String otype = afterChangeNoJson.getString("OTYPE");
                            map.put(beforeChangeNo, beforeChangeNo);
                        }
                    } else if ("替换".equals(type) || "修改".equals(type)) {
                        JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(afterChangeNo, RTPlmConstant.VIEW_DESIGN);
                        if (afterChangeNoJson != null) {
                            String id = afterChangeNoJson.getString("OID");
                            String otype = afterChangeNoJson.getString("OTYPE");
                            map.put(beforeChangeNo, beforeChangeNo);
                        }
                    }
                }
            }
        }
        return map;
    }

    public Map removeObjectMap(ChgFormVO chgFormVO) {
        Map map = new HashMap();
        //表单内容
        String formData = chgFormVO.getFormData();
        if (StringUtils.isNotBlank(formData)) {
            JSONObject formDataJson = JSONObject.parseObject(formData);
            JSONArray subform47946 = formDataJson.getJSONArray("subform47946");
            JSONArray subform57714 = formDataJson.getJSONArray("subform57714");
            if (CollectionUtils.isNotEmpty(subform47946)) {
                for (int i = 0; i < subform47946.size(); i++) {
                    String beforeChangeNo = subform47946.getJSONObject(i).getString("input67563");
                    String type = subform47946.getJSONObject(i).get("radio81926").toString();
                    String afterChangeNo = subform47946.getJSONObject(i).getString("radio73127");
                    if ("图号升级".equals(type)) {
                        map.put(beforeChangeNo, beforeChangeNo);
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(subform57714)) {
                for (int i = 0; i < subform57714.size(); i++) {
                    String beforeChangeNo = subform57714.getJSONObject(i).getString("input36063");
                    String type = subform57714.getJSONObject(i).getString("input70284");//radio60862
                    String afterChangeNo = subform57714.getJSONObject(i).getString("input37516");
                    if ("删除".equals(type)) {
                        map.put(beforeChangeNo, beforeChangeNo);
                    } else if ("替换".equals(type) || "修改".equals(type)) {
                        map.put(beforeChangeNo, beforeChangeNo);
                    } else if ("增加".equals(type)) {
                        map.put(afterChangeNo, afterChangeNo);
                    }
                }
            }
        }
        return map;
    }

    private void buildAfterChangeObjDistribute(BigInteger ecaId) {
        IdentifierEntity entity = new IdentifierEntity();
        entity.setOid(ecaId);
        entity.setOtype("ty.inteplm.change.CTyChangeActivity");
        TyplmLoggerUtil.debug(log, () -> "eca对象标识为==>【{}】", () -> new Object[]{JSON.toJSONString(entity)});
        ChgFormVO chgFormVO = this.tyChangeExtService.getChgFormByEcaOid(entity);
        TyplmLoggerUtil.debug(log, () -> "获取的变更单为==>【{}】", () -> new Object[]{JSON.toJSONString(chgFormVO)});
        List<ECObjData> ecObjDataVOS = chgFormVO.getEcObjDataVOS();
        Map<String, Object> params = new HashMap();
        params.put("baseObjectOid", chgFormVO.getEcnOid());
        params.put("baseObjectOtype", chgFormVO.getEcnOtype());
        params.put("status", WorkFlowContainerStatusEnum.PROCESSING.getValue());
        List<WorkFlowContainer> workFlowContainers = this.typlmWorkFlowContainerService.simpleQueryListByParams(params);
        TyplmLoggerUtil.debug(log, () -> "通过ecn获取的流程容器为==>【{}】", () -> new Object[]{JSON.toJSONString(workFlowContainers)});
        if (!CollUtil.isEmpty(workFlowContainers)) {
            WorkFlowContainer workFlowContainer = (WorkFlowContainer) workFlowContainers.get(0);
            this.typlmFlowObjectTaskLinkService.initInfoByDataBase(workFlowContainer, ecObjDataVOS);
            Map<BigInteger, List<ECObjData>> ecObjMap = (Map) ecObjDataVOS.stream().collect(Collectors.groupingBy(ECObjDataVO::getMasteredoid));
            List<ECObjData> ecObjDataList = chgFormVO.getEcAffectVOS();
            if (!CollUtil.isEmpty(ecObjDataList) && ecObjMap != null) {
                for (ECObjData ecObjData : ecObjDataList) {
                    List<ECObjData> ecObjDataOriList = (List) ecObjMap.get(ecObjData.getMasteredoid());
                    if (!CollUtil.isEmpty(ecObjDataOriList)) {
                        ECObjData ecObjDataOri = (ECObjData) ecObjDataOriList.get(0);
                        ecObjData.setTaskdefkey(ecObjDataOri.getTaskdefkey());
                        ecObjData.setTaskname(ecObjDataOri.getTaskname());
                        this.typlmFlowObjectTaskLinkService.update(workFlowContainer, ecObjData);
                    }
                }

            }
        }
    }

    public List<BigInteger> getEcaObjListOid(ChgActivityDO chgActivityDO) {
        List<ECObjData> ecObjDataList = typlmEngineeringChangeService.getChangeAfterByECA(new IdentifierEntity(chgActivityDO.getOid(), chgActivityDO.getOtype()));
        List<BigInteger> ecaObjList = new ArrayList<>();
        if (!ecObjDataList.isEmpty()) {
            ecaObjList = ecObjDataList.stream().map(ECObjData::getOid).collect(Collectors.toList());
        }
        return ecaObjList;
    }

    /**
     * 构建变更后对象
     *
     * @param chgActivityDO
     * @param boid
     * @param botype
     * @param chgActRecordLinkDOList
     */
    public void buildEcAffectVOList(ChgActivityDO chgActivityDO, BigInteger boid, String botype, List<ChgActRecordLinkDO> chgActRecordLinkDOList) {

        ChgActRecordLinkDO chgActRecordLinkDO = new ChgActRecordLinkDO();
        chgActRecordLinkDO.setAoid(chgActivityDO.getOid());
        chgActRecordLinkDO.setAotype(chgActivityDO.getOtype());
        chgActRecordLinkDO.setBoid(boid);
        chgActRecordLinkDO.setBotype(botype);
        chgActRecordLinkDO.setOid(snowflakeIdComponent.getInstance().nextId());
        chgActRecordLinkDO.setOtype(TableTypeConstrant.TY_CHGACTRECORDLINK_OTYPE);
        chgActRecordLinkDO.setBranchid(chgActivityDO.getBranchid());
        TyplmEntityBaseUtil.fillCommonFieldForCreate(chgActRecordLinkDO);
        chgActRecordLinkDOList.add(chgActRecordLinkDO);
    }

    public ChgActivityDO getChgActivityDO(String chgNoticeOid) {
        Example chgNoticeActivityLinkDOExample = new Example(ChgNoticeActivityLinkDO.class);
        chgNoticeActivityLinkDOExample.createCriteria().andEqualTo("aoid", new BigInteger(chgNoticeOid));
        ChgNoticeActivityLinkDO chgNoticeActivityLinkDO = typlmChgNoticeActivityLinkMapper.selectByExample(chgNoticeActivityLinkDOExample).get(0);
        Example chgActivityDOExample = new Example(ChgActivityDO.class);
        chgActivityDOExample.createCriteria().andEqualTo("oid", chgNoticeActivityLinkDO.getBoid());
        return typlmChgActivityMapper.selectByExample(chgActivityDOExample).get(0);
    }

    private Map<BigInteger, ChgActRelDataLinkDO> getActivityAndRelDataLinkMap(List<ChgActivityVO> ecaList) {
        Map<BigInteger, ChgActRelDataLinkDO> result = new HashMap();
        List<BigInteger> actOidList = (List) ecaList.stream().map(ChgActivityDO::getOid).collect(Collectors.toList());
        List<ChgActRelDataLinkDO> chgActRelDataLinkDOS = BatchQueryHelper.batchSplitQuery(actOidList, this::metaSelectChgActRelDataLinkByAoids);
        if (CollUtil.isNotEmpty(chgActRelDataLinkDOS)) {
            result = (Map) chgActRelDataLinkDOS.stream().collect(Collectors.toMap(ChgActRelDataLinkDO::getOid, (item) -> item, (a, b) -> a));
        }

        return result;
    }

    private List<ChgActRelDataLinkDO> metaSelectChgActRelDataLinkByAoids(Collection<BigInteger> actOidList) {
        return BatchQueryHelper.queryExampleColumnIn(actOidList, ChgActRelDataLinkDO.class, "aoid", this.typlmChgActRelDataLinkMapper);
    }

    private List<ChgActivityVO> getEcaByEcnId(BigInteger ecnId) {
        TyplmLoggerUtil.debug(log, () -> "根据ecnId【{}】查询eca集合", () -> new Object[]{ecnId});
        ChgNoticeDO chgNoticeDO = this.typlmChgNoticeQueryService.selectByPrimaryKey(ecnId);
        if (Objects.isNull(chgNoticeDO)) {
            TyException.throwSingleTyExceptionVarargs(ResponseCodeEnum.BIZ_OBJECT_NOT_FOUND, new String[]{ecnId.toString()});
        }

        return this.typlmChangeLinkService.queryECAByECO(chgNoticeDO);
    }

    private List<ECObjDataVO> checkObjectCanChange(List<ECObjDataVO> ecaChangeBeforeObjects) {
        List<ECObjDataVO> result = new ArrayList();
        if (CollUtil.isEmpty(ecaChangeBeforeObjects)) {
            return result;
        } else {
            Map<String, List<ECObjDataVO>> typeListMap = (Map) ecaChangeBeforeObjects.stream().collect(Collectors.groupingBy(ECObjDataVO::getOtype));
            Map<String, List<BigInteger>> otypeToBranchIdListMap = new HashMap();

            for (Map.Entry<String, List<ECObjDataVO>> entry : typeListMap.entrySet()) {
                String type = (String) entry.getKey();
                List<ECObjDataVO> value = (List) entry.getValue();
                List<BigInteger> masteredList = (List) value.stream().map(ECObjDataVO::getMasteredoid).distinct().collect(Collectors.toList());
                List<BasicObjectDTO> list = this.typlmCommonIterateService.batchQueryObjLastVersionByMasterId(masteredList, type);
                if (CollectionUtils.isNotEmpty(list)) {
                    for (BasicObjectDTO objectDTO : list) {
                        List<BigInteger> branchids = (List) otypeToBranchIdListMap.computeIfAbsent(objectDTO.getOtype(), (k) -> new ArrayList());
                        branchids.add(objectDTO.getBranchid());
                    }
                }
            }

            if (CollUtil.isEmpty(otypeToBranchIdListMap)) {
                return ecaChangeBeforeObjects;
            } else {
                for (Map.Entry<String, List<ECObjDataVO>> entry : typeListMap.entrySet()) {
                    if (otypeToBranchIdListMap.containsKey(entry.getKey())) {
                        List<BigInteger> branchids = (List) otypeToBranchIdListMap.get(entry.getKey());
                        if (CollectionUtils.isNotEmpty(branchids)) {
                            for (ECObjDataVO ecObjDataVO : (List<ECObjDataVO>) entry.getValue()) {
                                if (branchids.contains(ecObjDataVO.getBranchid())) {
                                    result.add(ecObjDataVO);
                                }
                            }
                        }
                    }
                }

                return result;
            }
        }
    }

    private void batchInitChgAfterObjectList(List<ECObjDataVO> ecObjDataVOList, BigInteger userOid, List<BasicObjectDTO> lastVersionObjMap, Map<BigInteger, ChgActRecordLinkDO> recordLinkDOMap, List<IdentifierEntity> chgAfterObjectList) {
        if (!CollUtil.isEmpty(ecObjDataVOList)) {
            Map<Integer, List<CommonIteratorVO>> changeStrategyMap = new HashMap();
            List<BusinessObjectVO> existNewVersionList = new ArrayList();

            for (ECObjDataVO ecObjDataVO : ecObjDataVOList) {
                List<BasicObjectDTO> basicObjectDTOList = (List) lastVersionObjMap.stream().filter((item) -> item.getMasteredoid().equals(ecObjDataVO.getMasteredoid())).collect(Collectors.toList());
                basicObjectDTOList = this.filterBasicObjectDTOS(ecObjDataVO, basicObjectDTOList);
                if (CollUtil.isEmpty(basicObjectDTOList)) {
                    return;
                }

                BasicObjectDTO basicObjectDTO = (BasicObjectDTO) basicObjectDTOList.get(0);
                TyplmLoggerUtil.debug(log, () -> "最新小版本的Branchid为==>【{}】，变更前对象的Branchid为==>【{}】", () -> new Object[]{basicObjectDTO.getBranchid(), ecObjDataVO.getBranchid()});
                boolean isRevise = ecObjDataVO.getBranchid().equals(basicObjectDTO.getBranchid());
                if (isRevise) {
                    Integer changeStrategy = this.getChangeStrategyValue(ecObjDataVO.getChangeStrategy());
                    this.putChangeStrategyMap(ecObjDataVO, userOid.toString(), changeStrategy, changeStrategyMap);
                } else {
                    BusinessObjectVO businessObjectVO = new BusinessObjectVO();
                    businessObjectVO.setTypeDefName(basicObjectDTO.getOtype());
                    businessObjectVO.setId(basicObjectDTO.getOid());
                    businessObjectVO.setOtype(basicObjectDTO.getOtype());
                    ecObjDataVO.setOid(basicObjectDTO.getOid());
                    existNewVersionList.add(businessObjectVO);
                }
            }

            List<BusinessObjectVO> newBusinessList = new ArrayList();
            if (CollUtil.isNotEmpty(changeStrategyMap)) {
                for (Map.Entry<Integer, List<CommonIteratorVO>> entry : changeStrategyMap.entrySet()) {
                    newBusinessList.addAll(this.typlmIterationService.batchNewVersion((List) entry.getValue(), (Integer) entry.getKey()));
                }
            }

            newBusinessList.addAll(existNewVersionList);
            if (CollUtil.isNotEmpty(newBusinessList)) {
                for (BusinessObjectVO objectVO : newBusinessList) {
                    boolean isCreatLink = ObjectUtil.isEmpty(recordLinkDOMap.get(objectVO.getId()));
                    if (isCreatLink) {
                        IdentifierEntity chgAfterObject = new IdentifierEntity(objectVO.getId(), objectVO.getOtype());
                        chgAfterObjectList.add(chgAfterObject);
                    }
                }
            }

        }
    }

    private List<BasicObjectDTO> filterBasicObjectDTOS(ECObjDataVO ecObjDataVO, List<BasicObjectDTO> lastVersionObjs) {
        String otype = ecObjDataVO.getOtype();
        if (!TyEntityMapperUtil.getOtypeByClass(PartDO.class).equals(otype)) {
            return lastVersionObjs;
        } else {
            lastVersionObjs = (List) lastVersionObjs.stream().filter((obj) -> TyplmEntityBaseUtil.isEmptyOid(ecObjDataVO.getViewDefOid()) || ecObjDataVO.getViewDefOid().equals(obj.getViewdefoid())).filter((obj) -> org.apache.commons.lang3.StringUtils.isBlank(ecObjDataVO.getVariation1()) || ecObjDataVO.getVariation1().equals(obj.getVariation1())).filter((obj) -> org.apache.commons.lang3.StringUtils.isBlank(ecObjDataVO.getVariation2()) || ecObjDataVO.getVariation2().equals(obj.getVariation2())).collect(Collectors.toList());
            return lastVersionObjs;
        }
    }

    public void createEcaLinkChgAfterObject(BigInteger ecaId, List<IdentifierEntity> chgAfterObjectList) {
        ChgActivityDO chgActivityDO = this.typlmChgActivityService.selectByPrimaryKey(ecaId);
        TyplmLoggerUtil.debug(log, () -> "根据ecaId【{}】获取的变更活动为==>【{}】", () -> new Object[]{ecaId, JSON.toJSONString(chgActivityDO)});
        List<ChgNoticeVO> chgNoticeVOS = this.typlmChgNoticeActivityLinkService.queryECOByECABranchId(chgActivityDO);
        WorkFlowContainer workFlowContainer = null;
        if (CollUtil.isNotEmpty(chgNoticeVOS)) {
            ChgNoticeVO chgNotice = (ChgNoticeVO) chgNoticeVOS.get(0);
            Map<String, Object> params = new HashMap();
            params.put("baseObjectOid", chgNotice.getOid());
            params.put("baseObjectOtype", chgNotice.getOtype());
            List<WorkFlowContainer> workFlowContainers = this.typlmWorkFlowContainerService.simpleQueryListByParams(params);
            TyplmLoggerUtil.debug(log, () -> "通过ecn获取的流程容器为==>【{}】", () -> new Object[]{JSON.toJSONString(workFlowContainers)});
            if (CollUtil.isNotEmpty(workFlowContainers)) {
                workFlowContainer = (WorkFlowContainer) workFlowContainers.stream().filter((workFlow) -> workFlow.getStatus() < WorkFlowContainerStatusEnum.COMPLETED.getValue()).findFirst().orElse((WorkFlowContainer) null);
            }
        }

        List<ChgActRecordLinkDO> actRecordLinkDOList = new ArrayList();
        List<BigInteger> partIds = new CopyOnWriteArrayList();
        List<ECObjDataVO> mpm = new CopyOnWriteArrayList();
        chgAfterObjectList.parallelStream().forEach((item) -> {
            if (!"ty.inteplm.mpm.CTyMPMProcessPlan".equals(item.getOtype()) && !"ty.inteplm.mpm.CTyMPMOperation".equals(item.getOtype())) {
                if ("ty.inteplm.part.CTyPart".equals(item.getOtype())) {
                    partIds.add(item.getOid());
                }
            } else {
                ECObjDataVO ecObjDataVO = new ECObjDataVO();
                ecObjDataVO.setOid(item.getOid());
                ecObjDataVO.setOtype(item.getOtype());
                mpm.add(ecObjDataVO);
            }

        });
        List<BigInteger> bigIntegers = Collections.emptyList();
        if (!org.springframework.util.CollectionUtils.isEmpty(partIds)) {
            CalculatePartRootDTO calculatePartRootDTO = new CalculatePartRootDTO();
            calculatePartRootDTO.setNowPartList(partIds);
            bigIntegers = this.typlmPartBomFlowObjectService.batchCalculatePartRootNode(calculatePartRootDTO);
        }

        this.typlmMpmWorkFlowAdaptationService.batchBuildMpmStructure(mpm);
        Map<BigInteger, ECObjDataVO> mpmMap = (Map) mpm.stream().collect(Collectors.toMap(ECObjDataVO::getRefObjectOid, (item) -> item, (i, j) -> i));

        for (IdentifierEntity identifierEntity : chgAfterObjectList) {
            ChgActRecordLinkDO recordLinkDO = new ChgActRecordLinkDO();
            recordLinkDO.setOid(this.snowflakeIdComponent.getInstance().nextId());
            recordLinkDO.setAoid(chgActivityDO.getOid());
            recordLinkDO.setBranchid(chgActivityDO.getBranchid());
            recordLinkDO.setBoid(identifierEntity.getOid());
            recordLinkDO.setBotype(identifierEntity.getOtype());
            EntityBaseUtil.fillCommonFieldForCreate(recordLinkDO);
            if (!"ty.inteplm.mpm.CTyMPMProcessPlan".equals(identifierEntity.getOtype()) && !"ty.inteplm.mpm.CTyMPMOperation".equals(identifierEntity.getOtype())) {
                if ("ty.inteplm.part.CTyPart".equals(identifierEntity.getOtype())) {
                    if (!org.springframework.util.CollectionUtils.isEmpty(bigIntegers) && bigIntegers.contains(identifierEntity.getOid())) {
                        recordLinkDO.setTypeMarkFlag(1);
                    } else {
                        recordLinkDO.setTypeMarkFlag(0);
                    }
                }
            } else {
                ECObjDataVO ecObjDataVO = (ECObjDataVO) mpmMap.get(identifierEntity.getOid());
                recordLinkDO.setTypeMarkFlag(ecObjDataVO.getTypeMarkFlag());
            }

            TyplmLoggerUtil.debug(log, () -> "eca与变更后对象的关联关系为==>【{}】", () -> new Object[]{JSON.toJSONString(recordLinkDO)});
            actRecordLinkDOList.add(recordLinkDO);
            if (workFlowContainer != null) {
                this.typlmFlowContainerObjectService.insertRuFlowObject(workFlowContainer, identifierEntity);
                TyAccountContext.removeBizCommonHolderMapValue("relativeEntityList");
            }
        }

        this.typlmChgActRecordLinkService.batchInsertSelective(actRecordLinkDOList);
    }

    private void reviseMpmObject(Map<String, List<ECObjDataVO>> eCObjDataMap, List<ECObjDataVO> ecaBeforeObjectList, List<IdentifierEntity> chgAfterObjectList) {
        ArrayList<CommonIteratorVO> mpmEntityList = new ArrayList();
        if (eCObjDataMap.containsKey("ty.inteplm.mpm.CTyMPMProcessPlan")) {
            List<ECObjDataVO> mpmProcessPlan = (List) eCObjDataMap.get("ty.inteplm.mpm.CTyMPMProcessPlan");
            if (CollUtil.isNotEmpty(mpmProcessPlan)) {
                this.buildIteratorVO(mpmProcessPlan, mpmEntityList);
                eCObjDataMap.remove("ty.inteplm.mpm.CTyMPMProcessPlan");
                ecaBeforeObjectList.removeAll(mpmProcessPlan);
            }
        }

        if (eCObjDataMap.containsKey("ty.inteplm.mpm.CTyMPMOperation")) {
            List<ECObjDataVO> mpmOperation = (List) eCObjDataMap.get("ty.inteplm.mpm.CTyMPMOperation");
            if (CollUtil.isNotEmpty(mpmOperation)) {
                this.buildIteratorVO(mpmOperation, mpmEntityList);
                eCObjDataMap.remove("ty.inteplm.mpm.CTyMPMOperation");
                ecaBeforeObjectList.removeAll(mpmOperation);
            }
        }

        if (CollUtil.isNotEmpty(mpmEntityList)) {
            for (HashMap<String, IdentifierEntity> hashMap : this.typlmIterationService.batchNewVersionMpmObj(mpmEntityList)) {
                IdentifierEntity identifierEntity = (IdentifierEntity) hashMap.get("new");
                chgAfterObjectList.add(identifierEntity);
            }
        }

    }

    private void buildIteratorVO(List<ECObjDataVO> ecObjDataVOS, ArrayList<CommonIteratorVO> iteratorVOList) {
        for (ECObjDataVO ecObjDataVO : ecObjDataVOS) {
            CommonIteratorVO commonIteratorVO = new CommonIteratorVO();
            commonIteratorVO.setId(ecObjDataVO.getOid().toString());
            commonIteratorVO.setSubfolderoid(ecObjDataVO.getSubfolderoid().toString());
            commonIteratorVO.setTypeDefName(ecObjDataVO.getOtype());
            TyplmLoggerUtil.debug(log, () -> "通用迭代对象为==>【{}】", () -> new Object[]{JSON.toJSONString(commonIteratorVO)});
            iteratorVOList.add(commonIteratorVO);
        }

    }


    private void putChangeStrategyMap(ECObjDataVO ecObjDataVO, String userOid, Integer changeStrategy, Map<Integer, List<CommonIteratorVO>> changeStrategyMap) {
        CommonIteratorVO commonIteratorVO = new CommonIteratorVO();
        commonIteratorVO.setId(ecObjDataVO.getOid().toString());
        commonIteratorVO.setSubfolderoid(ecObjDataVO.getSubfolderoid().toString());
        commonIteratorVO.setTypeDefName(ecObjDataVO.getOtype());
        commonIteratorVO.setUserID(userOid);
        TyplmLoggerUtil.debug(log, () -> "通用迭代对象为==>【{}】", () -> new Object[]{JSON.toJSONString(commonIteratorVO)});
        List<CommonIteratorVO> iteratorVOList = (List) changeStrategyMap.get(changeStrategy);
        TyplmLoggerUtil.debug(log, () -> "通过变更策略获取的通用迭代对象集合为==>【{}】", () -> new Object[]{JSON.toJSONString(iteratorVOList)});
        if (CollUtil.isEmpty(iteratorVOList)) {
            List<CommonIteratorVO> newVersionList = new ArrayList();
            newVersionList.add(commonIteratorVO);
            changeStrategyMap.put(changeStrategy, newVersionList);
        } else {
            iteratorVOList.add(commonIteratorVO);
        }

    }

    private Integer getChangeStrategyValue(String strategy) {
        Integer changeStrategy = TyChangeMngConstant.getChangeStrategyValueMap(strategy);
        if (Objects.isNull(changeStrategy)) {
            changeStrategy = TyChangeMngConstant.getChangeStrategyValueMap("Change");
        }

        return changeStrategy;
    }

    public List<IbaDTO> buildSaveIbaDTO(Map<String, List<String>> ibaMap) {
        List<IbaDTO> bomLinkIbaAttrs = new ArrayList<>();
        if (ibaMap != null) {
            for (String key : ibaMap.keySet()) {
                List<String> value = ibaMap.get(key);
                if (CollectionUtils.isNotEmpty(value)) {
                    IbaDTO ibadto = new IbaDTO();
                    ibadto.setKey(key);
                    ibadto.setValue(value.get(0));
                    bomLinkIbaAttrs.add(ibadto);
                }
            }
        }
        return bomLinkIbaAttrs;
    }

    public boolean deleteTheBuildRule(BigInteger boid) {
        if (boid == null){
            return false;
        }
        Example example = new Example(CADBuildRuleDO.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("boid",boid);
        List<CADBuildHistoryDO> cadBuildHistoryDOS = typlmCADBuildHistoryMapper.selectByExample(example);
        if (CollUtil.isNotEmpty(cadBuildHistoryDOS)){
            CADBuildHistoryDO cadBuildHistoryDO = cadBuildHistoryDOS.get(0);
            Example cadBuildRuleExample = new Example(CADBuildRuleDO.class);
            criteria = cadBuildRuleExample.createCriteria();
            criteria.andEqualTo("oid",cadBuildHistoryDO.getBuildruleid());
            typlmCADBuildRuleMapper.deleteByExample(cadBuildRuleExample);
            Example cadBuildRuleHistoryExample = new Example(CADBuildHistoryDO.class);
            criteria = cadBuildRuleHistoryExample.createCriteria();
            criteria.andEqualTo("buildruleid",cadBuildHistoryDO.getBuildruleid());
            typlmCADBuildHistoryMapper.deleteByExample(cadBuildRuleHistoryExample);
        }
        return true;
    }
    public BigInteger randomCodeGenerator() {
        Random random = new Random();
        long number = random.nextLong(); // 生成一个长整型随机数
        // 确保生成的数字是正数且不超过999999999999999999（即18位数字的最大值）
        number = Math.abs(number) % 999999999999999999L;
        // 转换为字符串并保证长度为18位
        String code = String.format("%018d", number);
        return new BigInteger(code);
    }
}
